package com.mccken.demo.io.netty.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;

/**
 * Hessian序列化工具类
 * 
 * @program: mccken-collect
 * @description:
 * @author: mccken
 * @create: 2022-04-30 18:19
 **/
public class HessianSerializer implements MySerializer{

	@Override
	public <T> byte[] serialize(T obj) {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		HessianOutput ho = new HessianOutput(os);

		try {
			ho.writeObject(obj);
			ho.flush();
			return os.toByteArray();
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			try {
				ho.close();
				os.close();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
	}

	@Override
	public <T> T deseralize(byte[] bytes, Class<T> clazz) {

		ByteArrayInputStream is = new ByteArrayInputStream(bytes);
		HessianInput hi = new HessianInput(is);
		try {
			return (T)hi.readObject(clazz);
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
	}
}
